package com.cyberfans.shop.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cyberfans.shop.dao.IDAO;

@Transactional
public abstract class DaoSupport implements IDAO {
	@PersistenceContext
	protected EntityManager em;

	/* (non-Javadoc)
	 * @see com.cyberfans.shop.dao.IDAO#save(java.lang.Object)
	 */
	@Override
	public void save(Object entity) {
		em.persist(entity);
	}

	/* (non-Javadoc)
	 * @see com.cyberfans.shop.dao.IDAO#update(java.lang.Object)
	 */
	@Override
	public void update(Object entity) {
		em.merge(entity);
	}

	/* (non-Javadoc)
	 * @see com.cyberfans.shop.dao.IDAO#delete(java.lang.Object)
	 */
	@Override
	public <T> void delete(Class<T> entityClass, Object entityId) {
//		em.remove(em.getReference(entityClass, entityId));
		delete(entityClass, new Object[]{entityId});
	}

	/* (non-Javadoc)
	 * @see com.cyberfans.shop.dao.IDAO#delete(java.lang.Object[])
	 */
	@Override
	public <T> void delete(Class<T> entityClass, Object[] entityIds) {
		for (Object entityId : entityIds) {
			delete(entityClass, entityId);
		}
	}

	/* (non-Javadoc)
	 * @see com.cyberfans.shop.dao.IDAO#find(java.lang.Class, java.lang.Object)
	 */
	@Override
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public <T> T find(Class<T> entityClass, Object entityId) {
		return em.find(entityClass, entityId);
	}
	
}
